﻿using GameBasic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

namespace VCity
{
    public class Preloader : MonoSingleton<Preloader>
    {
        public enum Type
        {
            None,
            Server,
            Client,
            Host,
        }

        [Header("Config")]
        public Type type;
        public bool loadConfig;
        public ConfigData config;

        public bool IsServer => type == Type.Server;
        public bool IsHost => type == Type.Host;
        public bool IsClient => type == Type.Client;

        private void Start()
        {
#if !UNITY_EDITOR
            loadConfig = true;
#endif
            if (loadConfig)
            {
                string configPath = Path.Combine(Path.Combine(Application.streamingAssetsPath, "config.json"));
                if (IsServer)
                {
                    var read = GameBasic.IO.FileOperation.Read(configPath);
                    read.Execute();
                    this.config = JsonUtility.FromJson<ConfigData>(read.data);

                    StartImpl(config);
                }
                else
                {
                    StartCoroutine(GameResources.LoadFromUri(configPath, request =>
                    {
                        if (request.result == UnityWebRequest.Result.Success)
                        {
                            this.config = JsonUtility.FromJson<ConfigData>(request.downloadHandler.text);
                        }
                        else
                        {
                            Debug.Log($"{request.result}: Cannot load config from {configPath} ");
                        }

                        StartImpl(config);
                    }));
                }
            }
            else
            {
                StartImpl(config);
            }
        }

        void StartImpl(ConfigData config)
        {
            if (config != null)
            {
                NetworkMain.Instance.Init(config);

                // framerate
                if (config.targetFrameRate > 0 && type == Type.Client)
                    Application.targetFrameRate = config.targetFrameRate;
                else if (config.targetFrameRateServer > 0 && type == Type.Server)
                {
                    Debug.Log($"TargetFrameRate: {config.targetFrameRateServer}");
                    Application.targetFrameRate = config.targetFrameRateServer;
                }
            }

            bool loadClientScene = false;
            switch (type)
            {
                case Type.None:
                    loadClientScene = true;
                    break;
                case Type.Host:
                    //StartHost();
                    NetworkMain.Instance.StartHost();
                    loadClientScene = true;
                    break;
                case Type.Server:
                    NetworkMain.Instance.StartServer();
                    break;
                case Type.Client:
                    NetworkMain.Instance.StartClient();
                    loadClientScene = true;
                    break;
                default:
                    break;
            }

            // init
            //#if UNITY_EDITOR
            //            loadClientScene = true;
            //#endif
            if (loadClientScene && ClientMain.Instance == null)
            {
                var load = SceneManager.LoadSceneAsync("ClientMain", LoadSceneMode.Additive);
                load.completed += job =>
                {
                    SceneManager.SetActiveScene(SceneManager.GetSceneByBuildIndex(1));
                };
            }
        }

        //void StartClient()
        //{
        //    var mng = NetworkManager.Singleton;
        //    var t = (WebSocketTransport)NetworkManager.Singleton.NetworkConfig.NetworkTransport;
        //    if (mng.StartClient())
        //    {
        //        mng.SceneManager.SetClientSynchronizationMode(LoadSceneMode.Additive);
        //        mng.SceneManager.VerifySceneBeforeLoading = (index, name, mode) => false;

        //        Debug.Log($"Client started on {t.ConnectAddress}:{t.Port}");
        //    }
        //    else
        //    {
        //        Debug.Log($"Failed to start client on {t.ConnectAddress}:{t.Port}");
        //    }
        //}

        //void StartHost()
        //{
        //    var mng = NetworkManager.Singleton;
        //    var t = (WebSocketTransport)NetworkManager.Singleton.NetworkConfig.NetworkTransport;
        //    if (mng.StartHost())
        //    {
        //        mng.SceneManager.SetClientSynchronizationMode(LoadSceneMode.Additive);
        //        mng.SceneManager.VerifySceneBeforeLoading = (index, name, mode) => false;

        //        NetServer server = Instantiate(serverPrefab);
        //        server.GetComponent<NetworkObject>().Spawn(destroyWithScene: false);

        //        Debug.Log($"Host started on {t.ConnectAddress}:{t.Port}");
        //    }
        //    else
        //    {
        //        Debug.Log($"Failed to start host {t.ConnectAddress}:{t.Port}");
        //    }
        //}
    }
}